<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>流程设计器</title>
    <link rel="stylesheet" href="css/layui.css" media="all">
    <link rel="stylesheet" href="css/contextmenu.css" media="all">
    <link rel="stylesheet" href="css/desgin.css" media="all">
    <style>
        html {
            width: 100%;
            height: 100%;
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }

        body {
            width: 100%;
            height: 100%;
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: 'Avenir', Helvetica, Arial, sans-serif;
            font-size: 13px;
            line-height: 22px;
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
            color: #2c3e50;
        }

        .container {
            height: 100%;
            width: calc(100%-50px);
            display: flex;
            flex-direction: row;
            cursor: pointer;
        }

        #flowMain {
            height: 100%;
            width: 100%;
            background-image: url(images/flowbg.gif);

        }

        .flowop {
            width: 50px;
            height: 100%;
            display: flex;
            flex-direction: column;
            background-color: #EEEEEE;
        }

        ._jsPlumb_connector {
            cursor: pointer;
        }

        ._jsPlumb_endpoint {
            cursor: crosshair;
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="flowop">
            <button type="button" class="layui-btn layui-btn-xs" onclick="choose()" style="height: 30px;" title="选择">
                <img src="images/choose.png" style="width: 20px;height: 20px;">
            </button>
            <button type="button" class="layui-btn layui-btn-xs" onclick="connect()" style="height: 30px;" title="连接">
                <img src="images/transition.png" style="width: 25px;height: 25px;">
            </button>
            <button type="button" class="layui-btn layui-btn-xs" onclick="move()" style="height: 30px;" title="移动">
                <img src="images/move.png" style="width: 25px;height: 25px;">
            </button>
            <button type="button" class="layui-btn layui-btn-xs" onclick="save()" style="height: 30px;" title="保存">
                <img src="images/save.png" style="width: 22px;height: 22px;">
            </button>
        </div>
        <div id="flowMain">
            <div class="nodeTitle">
                <div style="padding: 12px;">
                    <h3>重命名节点标题：</h3>
                    <input type="text" name="nodeTitle" placeholder="请输入节点标题" lay-verify="required" placeholder="" autocomplete="off" class="layui-input" style="margin:10px 0px;">
                    <div class="layui-layer-btn" style="padding:0;float: right;">
                        <button data-type="nodeSubmit" class="layui-btn layui-btn-sm layui-btn-primary layui-btn-event" style="margin:0;">保存</button>
                        <button data-type="nodeClose" class="layui-btn layui-btn-sm layui-btn-primary layui-btn-event" style="margin:0;">关闭</button>
                    </div>
                </div>
            </div>
            <script type="text/x-mustache" id="jnode-template">
                <div class="jnode-panel" id="{{id}}" jnode="{{jnode}}" style="top:{{top}}px;left:{{left}}px">
                    <div class="jnode-box {{jnodeClass}}">{{{jnodeHtml}}}</div>
                </div>
            </script>
        </div>
    </div>
    <script src="js/jquery-1.10.2.min.js"></script>
    <script src="js/mustache.min.js"></script>
    <script src="js/jquery.jsPlumb-1.7.2.js"></script>
    <script src="js/jquery-ui.min.js"></script>
    <script src="js/contextmenu.js"></script>
    <script src="js/desgin.js"></script>
    <script>
        $(function() {
            importConfig();
            initContextMenu();
            initBodyClick();
            refreshDesgin();
        })

        //注册菜单事件
        function initContextMenu() {
            $.contextMenu({
                selector: '.container',
                callback: function(key, options) {

                },
                items: {
                    "addActivity": {
                        name: "新增活动",
                        callback: function(itemKey, opt, rootMenu, originalEvent) {
                            var e = window.event;
                            var left = e.pageX
                            var top = e.pageY
                            addActivity(getNewGuid(), "task", "活动", left, top);
                        }
                    }
                }
            });
            $.contextMenu({
                selector: ".bdc-primary-select",
                callback: function(key, options) {

                },
                items: {
                    "editActivity": {
                        name: "活动设置",
                        callback: function(itemKey, opt, rootMenu, originalEvent) {
                            var id = $($(opt.$trigger[0]).parent()).attr("id");
                            editActivity(id)
                        }
                    },
                    "deleteActivity": {
                        name: "删除活动",
                        callback: function(itemKey, opt, rootMenu, originalEvent) {
                            var id = $($(opt.$trigger[0]).parent()).attr("id");
                            deleteActivity(id)
                        }
                    }
                }
            });
            $.contextMenu({
                selector: "svg[select='2']",
                callback: function(key, options) {

                },
                items: {
                    "editTransition": {
                        name: "变迁设置",
                        callback: function(itemKey, opt, rootMenu, originalEvent) {
                            var id = $(opt.$trigger[0]).attr("id");
                            editTransition(id);
                        }
                    },
                    "deleteTransition": {
                        name: "删除变迁",
                        callback: function(itemKey, opt, rootMenu, originalEvent) {
                            var id = $(opt.$trigger[0]).attr("id");
                            deleteTransition(id);
                        }
                    }
                }
            });

        }

        //注册点击空白处事件
        function initBodyClick() {
            $('body').click(function(e) {
                var id = $(e.target).attr("id");
                if (id == "flowMain") {
                    cacneConnectLightSelect();
                    cancelNodeLightSelect();
                }
            })
        }

        //选择拖拽操作
        function choose() {
            cancelAllAutoConnect()
            var nodeList = getActivityList();
            for (var i = 0; i < nodeList.length; i++) {
                var element = nodeList[i];
                registDraggable(element.id);
            }
            //修改光标
            $(".container").css("cursor", "pointer");
            $("._jsPlumb_connector").css("cursor", "pointer");
            closeMultiMove();
        }

        //连接活动操作
        function connect() {
            var nodeList = getActivityList();
            for (var i = 0; i < nodeList.length; i++) {
                var element = nodeList[i];
                cancelDraggable(element.id);
                registAutoConnect(element.id);
            }
            //修改光标
            $(".container").css("cursor", "crosshair");
            $("._jsPlumb_connector").css("cursor", "crosshair");
            closeMultiMove();
        }

        //整体移动
        function move(){
            choose();
            $(".container").css("cursor", "move");
            $("._jsPlumb_connector").css("cursor", "move");
            startMultiMove();
        }

        //添加活动
        function addActivity(id, type, text, x, y) {
            renderActivity(id, type, text, x, y);
            console.log("addActivity");
        }

        //渲染活动
        function renderActivity(id, type, text, x, y) {
            var dataObj = {};
            dataObj.id = id;
            dataObj.left = x;
            dataObj.top = y;
            dataObj.jnode = type;
            if (type == "task") {
                dataObj.jnodeClass = "jnode-task bdc-primary";
            } else if (type == "start" || type == "end") {
                dataObj.jnodeClass = "jnode-task bdc-danger";
            }
            dataObj.jnodeHtml = "<span>" + text + "</span>";
            var targetHtml = Mustache.render($("#jnode-template").html(), dataObj);
            $("#flowMain").append(targetHtml);
            addDraggable(dataObj.id);
            initContextMenu();
            choose();
            //活动选中样式
            $(".bdc-primary").unbind("click").bind("click", function() {
                cancelNodeLightSelect();
                cacneConnectLightSelect();
                $(this).addClass("bdc-primary-select")
            })
        }

        //活动移动
        function moveActivity(id, x, y) {
            console.log("moveActivity" + id + "|" + "x:" + x + "★" + "y:" + y);
        }

        //删除活动
        function deleteActivity(id) {
            deleteNodeAndConnect(id);
            console.log("deleteActivity");
        }

        //活动设置
        function editActivity(id) {
            alert("活动设置" + id)
        }

        //获取所有活动节点
        function getActivityList() {
            var activityList = [];
            $("#flowMain .jnode-box").each(function(idx, elem) {
                var $elem = $(elem);
                activityList.push({
                    id: $elem.parent().attr('id'),
                    activity_type: $elem.parent().attr('jnode'),
                    activity_name: $elem.html().replace(/"/g, "'").replace(/[\t\n]/g, "").replace("<span>", "").replace("</span>", ""),
                    position_x: parseInt($elem.parent().css("left"), 10),
                    position_y: parseInt($elem.parent().css("top"), 10)
                });
            });
            return activityList;
        }

        //添加变迁（手动操作）
        function addTransition(connInfo) {
            var start_actvity_id = connInfo.sourceId;
            var end_activity_id = connInfo.targetId;
            console.log("addTransition");
        }

        //渲染变迁（代码添加）
        function renderTransition(id, start_actvity_id, end_activity_id) {
            connect();
            addConnect(id, start_actvity_id, end_activity_id)
            choose();
        }

        //删除变迁
        function deleteTransition(id) {
            deleteConnect(id);
            console.log("deleteTransition");
        }

        //变迁设置
        function editTransition(id) {
            alert("变迁设置" + id)
        }

        //检查变迁是否已存在
        function checkTransition(connection) {
            var start_actvity_id = connection.sourceId;
            var end_activity_id = connection.targetId;
            return true;
        }

        //获取所有变迁节点
        function getTransitionList() {
            var transitionList = [];
            $.each(jsPlumb.getAllConnections(), function(idx, connection) {
                transitionList.push({
                    id: connection.id,
                    start_actvity_id: connection.sourceId,
                    end_activity_id: connection.targetId,
                });
            });
            return transitionList;
        }

        //刷新设计器
        function refreshDesgin() {
            //活动
            var activityList = [
            {
                "id": "96e0add0-acd2-11ed-acf8-a7569faac9a5",
                "activity_type": "start",
                "activity_name": "开始",
                "position_x": 475,
                "position_y": 49
            },{
                "id": "03052ca0-ac08-11ed-bf36-83035172d4d6",
                "activity_type": "task",
                "activity_name": "申请",
                "position_x": 478,
                "position_y": 185
            },  {
                "id": "9e9c81c0-acd2-11ed-acf8-a7569faac9a5",
                "activity_type": "task",
                "activity_name": "审批",
                "position_x": 476,
                "position_y": 327
            },
            {
                "id": "04549000-ac08-11ed-bf36-83035172d4d6",
                "activity_type": "end",
                "activity_name": "结束",
                "position_x": 471,
                "position_y": 495
            }];
            for (var i = 0; i < activityList.length; i++) {
                var activity = activityList[i];
                renderActivity(activity.id, activity.activity_type, activity.activity_name, activity.position_x, activity.position_y)
            }
            //变迁
            var transitionList = [{
                "id": "xxxxx1",
                "start_actvity_id": "96e0add0-acd2-11ed-acf8-a7569faac9a5",
                "end_activity_id": "03052ca0-ac08-11ed-bf36-83035172d4d6",
            }, {
                "id": "xxxxx2",
                "start_actvity_id": "03052ca0-ac08-11ed-bf36-83035172d4d6",
                "end_activity_id": "9e9c81c0-acd2-11ed-acf8-a7569faac9a5",
            }, {
                "id": "xxxxx3",
                "start_actvity_id": "9e9c81c0-acd2-11ed-acf8-a7569faac9a5",
                "end_activity_id": "04549000-ac08-11ed-bf36-83035172d4d6",
            }];
            for (var i = 0; i < transitionList.length; i++) {
                var transition = transitionList[i];
                renderTransition(transition.id, transition.start_actvity_id, transition.end_activity_id);
            }
        }

        //获取所有节点及变迁json
        function save() {
            var activityList = getActivityList();
            console.log(activityList)
            var transitionList = getTransitionList();
            console.log(transitionList)
        }

        //导入默认配置
        function importConfig() {
            var config = {
                Anchor: "Bottom",
                Anchors: [null, null],
                ConnectionsDetachable: false,
                ConnectionOverlays: [
                    ['Arrow', { width: 10, length: 10, location: 1 }]
                ],
                Connector: "Straight",
                Container: null,
                DoNotThrowErrors: false,
                DragOptions: {},
                DropOptions: {},
                Endpoint: "Dot",
                EndpointOverlays: [],
                Endpoints: [null, null],
                EndpointStyle: { fillStyle: "#393D49", radius: 4, },
                EndpointStyles: [null, null],
                EndpointHoverStyle: null,
                EndpointHoverStyles: [null, null],
                HoverPaintStyle: null,
                LabelStyle: { color: "black" },
                LogEnabled: false,
                Overlays: [],
                MaxConnections: 1,
                PaintStyle: { lineWidth: 5, strokeStyle: "#456" },
                ReattachConnections: false,
                RenderMode: "svg",
                Scope: "jsPlumb_DefaultScope"
            };
            jsPlumb.importDefaults(config);
        }
    </script>
</body>

</html>